import random
import time
import requests

def set_user_agent(userAgentPath,encoding)->str:
    # 打开文件，换行读取
    with open(userAgentPath, "r" ,encoding=encoding) as f:
        file = f.readlines()
    item = []
    for agent in file:
         # 以换行符分割，转换为dict对象
        agent = eval(agent.replace('\n',''))
        item.append(agent)
    # 随机选取一个IP
    userAgent = random.choice(item)
    return userAgent

def get_random_proxy(filePath,encoding):
    # 打开文件，换行读取
    with open(filePath, "r" ,encoding=encoding) as f:
        file = f.readlines()
    # 遍历并分别存入列表，方便随机选取IP
    item = []
    for proxies in file:
         # 以换行符分割，转换为dict对象
        proxies = eval(proxies.replace('\n',''))
        item.append(proxies)
    # 随机选取一个IP
    proxies = random.choice(item)  
    return  proxies

def emulate_click(url, headers=None,proxy=None):
    # 使用requests发送请求，可以选择是否使用代理
    try:
        response = requests.get(url,headers=headers,proxies=proxy)
        if response.status_code == 200:
            print("Click successful!")
        else:
            print("Click failed with status code:", response.status_code)
    except requests.exceptions.ConnectionError:
        print("Failed to connect to the server")

# url = 'https://www.jiangshuntech.com/'
# url ='https://mp.weixin.qq.com/s/GPIJqD9jaY_QgbKeOpjGtw'
# url ='https://mp.weixin.qq.com/s/j2w6y1NgTDZ9d_iWfJrrYw'
url ='https://weibo.com/7247020398/OlHZV7epg'

# 解决中文乱码
encoding = 'utf-8'
userAgentPath = r'E:\project\py-pro\user-agent.txt'
filePath = r'E:\project\py-pro\IP.txt'
userAgent = set_user_agent(userAgentPath,encoding)
headers = {'User-Agent': userAgent}

for i in range(1,20):
    proxies = get_random_proxy(filePath,encoding)
    emulate_click(url,headers=headers,proxy=proxies)
    time.sleep(1)